package tests;

import static org.junit.Assert.*;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import model.datasource.DatabaseManager;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import common.Constants;

public class DatabaseTest
{
	private static final String table_name = "dummy";
	
	@Before
	public void setUp() throws SQLException
	{
		int res;
		DatabaseManager dm = DatabaseManager.getInstance();
		res = dm.initialize();
		assertEquals(Constants.OK,res);
		
		Connection conn = dm.getConnection();
		assertNotNull(conn);
		
		// check whether table does not exist
		ResultSet rs = conn.createStatement().executeQuery("SELECT name from sqlite_master WHERE type = 'table' AND name= '" + table_name + "'");
		assertFalse(rs.next()); // asset so entry does not exist
		
		res = conn.createStatement().executeUpdate("CREATE TABLE IF NOT EXISTS'" + table_name + "' ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT )");
		assertEquals(Constants.OK, res);
		
		rs.close();
		conn.close();
	}
	
	@After
	public void tearDown() throws SQLException
	{
		int res;
		DatabaseManager dm = DatabaseManager.getInstance();
		res = dm.initialize();
		assertEquals(Constants.DATABASE_INITIALIZED,res);
		
		Connection conn = dm.getConnection();
		assertNotNull(conn);
		
		res = conn.createStatement().executeUpdate("DROP TABLE IF EXISTS '" + table_name + "'");
		assertEquals(Constants.OK, res);
		
		conn.close();
	}
	
	@Test
	public void CreateEntries()
	{
		String query = "INSERT INTO " + table_name + "(name) VALUES(?)";
		DatabaseManager dm = DatabaseManager.getInstance();
		try
		{
			Connection conn = dm.getConnection();
			
			PreparedStatement statement = conn.prepareStatement(query);		
			statement.setString(1, "name1");
			
			int key = statement.executeUpdate();
			
			System.out.println(key);
			ResultSet rs = statement.getGeneratedKeys();
			while(rs.next())
			{
				System.out.println("key " + rs.getInt(1));
			}
			rs.close();
			conn.close();
		}
		catch(SQLException e)
		{
			e.printStackTrace();
		}
		
	}

}
